import type { BaseResponse, RequestOptions } from "../types";

// 全局接口基础配置
export const BASE_URL = "https://frankgrows.icu"; // 根据实际修改

/**
 * 通用请求函数
 * @param options 请求配置
 * @returns Promise<响应数据>
 */
export function request<T = any>(options: RequestOptions): Promise<T> {
  const {
    url,
    method = "GET",
    data = {},
    header = {},
    showLoading = false,
  } = options;

  // 显示加载中
  if (showLoading) {
    uni.showLoading({ title: "加载中..." });
  }

  // 自动注入 token
  const token = uni.getStorageSync("token");
  const authHeader = token ? { Authorization: `Bearer ${token}` } : {};

  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + url,
      method,
      data,
      header: {
        "Content-Type": "application/json",
        ...authHeader,
        ...header,
      },
      success: (res: UniApp.RequestSuccessCallbackResult) => {
        const response = res.data as BaseResponse<T>;
        
        if (response.code === 200 || response.code === 0) {
          resolve(response.data);
        } else {
          uni.showToast({
            title: response.message || "请求出错",
            icon: "none",
          });
          reject(response);
        }
      },
      fail: (err) => {
        uni.showToast({ title: "网络异常，请稍后再试", icon: "none" });
        reject(err);
      },
      complete: () => {
        if (showLoading) {
          uni.hideLoading();
        }
      },
    });
  });
}
